from pathlib import Path

from fastapi import UploadFile

from app.config import upload_file_config
from app.models.file_dto import FileDTO


def get_file_extension_name(file_original_name: str) -> str:
    """
    获取文件扩展名
    :param file_original_name: 原始文件名称
    :return: 文件扩展名
    """
    file_suffix = file_original_name.rsplit(".", maxsplit=1)[-1]
    return file_suffix


def save_file(file: UploadFile, path=None) -> FileDTO:
    """
    保存文件到本地
    :param path: 文件路径
    :param file:待保存文件
    :return: 保存后的文件路径
    """
    if path is None:
        path = upload_file_config.config.upload_path
    print("path:{}".format(path))
    dir_path = Path(path)
    if not dir_path.is_dir():
        dir_path.mkdir(parents=True, exist_ok=True)

    file_path = dir_path / file.filename
    # 异步保存文件到本地
    with open(file_path, "wb") as buffer:
        buffer.write(file.file.read())

    return FileDTO(file_name=file.filename,
                   file_path=file_path,
                   file_extension_name=get_file_extension_name(file_path.name),
                   old_file_name=file.filename)
